#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023-04-20 16:44
# @Author  : wsh
# @File    : routers.py
from fastapi import APIRouter, Header
from starlette.requests import Request

from config import USER_TOKEN
from model.db import reservoir_sensitivity, TbUsers
from model.db.mapper.company_mapper import company_is_exist, get_company_Bycode
from model.db.mapper.depart_mapper import get_depart_by_depart_id
from model.db.mapper.users_mapper import add_user, get_user_by_id, get_user_by_email, user_login, userName_is_exist, \
    activate_user, is_activate, update_user_info, update_user, update_users, deleteuser
from model.params import RoleNameEnum
from model.params.depart_params import DepartGetIdParam
from model.params.users_params import UserInfoParam, UserLoginParam, ActivateParam, UserID, \
    UserInfoUpdateParam, Activate_param, UserRegisterParam, RegUserParam
from model.redis.utils import redis_save_emailcode, redis_verify_email, redis_save_token, refresh_token, \
    redis_user_has_login_num, redis_delete_token
from util import success_res, obj_to_dict, SuccessCode, ErrorCode, error_res, get_email_code, create_token, img_util
from model.redis.utils import redis_save_emailcode, redis_verify_email, redis_save_token, refresh_token
from util import success_res, obj_to_dict, SuccessCode, ErrorCode, error_res, get_email_code, create_token, img_util, \
    DataNotExist, objs_to_dict
from util.access_token import parse_token
from .auth_routers import auth_router
from .code_routers import code_router

user_router = APIRouter(prefix="/user", tags=['用户管理'])
user_router.include_router(auth_router)


@user_router.post("/login", name="用户登录")
async def _add_user(param: UserLoginParam, request: Request):
    ip = request.scope["client"][0]
    verify = img_util.get_code(ip)
    verify: str
    # 验证验证码
    if verify.lower() != param.code.lower():
        return error_res(ErrorCode.LOGIN_CODE_ERROR)
    # 用户登录
    user = user_login(param.username, param.password, param.role_name);
    # 验证激活
    if user.is_authorize == 0:
        return error_res(ErrorCode.USER_NOT_ACTIVATED)
    payload = {
        "user_id": user.user_id,
        "user_name": user.user_name,
        "user_pwd": user.user_pwd,
        "role_name": user.role_name.value
    }
    token_key = USER_TOKEN.format(user.user_id)
    token = await request.app.state.redis.get(name=token_key)
    if token is None:
        token = create_token(payload)
        await redis_save_token(request, user.user_id, token, USER_TOKEN)
        return success_res({
            'user': obj_to_dict(user),
            'token': token
        }, SuccessCode.LOGIN)

    await refresh_token(request, user.user_id, token, USER_TOKEN)
    return success_res({
        'user': obj_to_dict(user),
        'token': token.decode()
    }, SuccessCode.USER_LOGGED_IN)


@user_router.post("/register", name="用户注册")
async def register(param: UserRegisterParam, request: Request):
    if userName_is_exist(param.user_name):
        return error_res(ErrorCode.USER_ISEXIST)
    company = get_company_Bycode(param.company_code)
    depart = get_depart_by_depart_id(param.depart_name)
    validate = await redis_verify_email(request, param.email, param.email_code)
    if validate == ErrorCode.EMAIL_CODE_ERROR:
        return error_res(validate)
    if validate == ErrorCode.EMAIL_CODE_ISNONE:
        return error_res(validate)
    group_id: int
    if param.role_name == RoleNameEnum.User.value:
        group_id = 1
    elif param.role_name == RoleNameEnum.Admin.value:
        group_id = 2
    user = RegUserParam(
        user_name=param.user_name,
        user_pwd=param.password,
        role_name=param.role_name,
        company_name=company.company_name,
        belong_post=param.depart_name,
        job_name=param.job_name,
        true_name=param.true_name,
        phone=param.phone,
        email=param.email,
        group_id=group_id,
        remark=param.remark
    )
    new_user = add_user(user)
    return success_res(obj_to_dict(new_user), SuccessCode.REGISTER)


@user_router.post("/activate", name="激活用户")
async def activate(param: Activate_param, token=Header('token')):
    payload = parse_token(token)
    user = is_activate(param.activate_user_id)
    if user is None:
        return error_res(ErrorCode.PATCH)
    if param.neither_activate==1:
        user = activate_user(user.user_id, payload.get('user_name'))
    else:
        user=deleteuser(param.activate_user_id)
    return success_res(obj_to_dict(user), SuccessCode.GET)


@user_router.post("/info", name="查询用户")
async def get_user_id(params: UserID, token=Header('token')):
    payload = parse_token(token)
    if payload.get('user_id') != params.user_id:
        return error_res(ErrorCode.USER_NO_PERMISSION)
    user = get_user_by_id(params.user_id)

    return success_res(obj_to_dict(user), SuccessCode.GET)


@user_router.post("/info/update", name="更新用户")
async def get_user_id(params: UserInfoUpdateParam, token=Header('token')):
    payload = parse_token(token)
    if payload.get('user_id') != params.user_id:
        return error_res(ErrorCode.USER_NO_PERMISSION)
    user = update_user_info(params)

    return success_res(obj_to_dict(user), SuccessCode.PUT)


@user_router.post("", name="添加用户")
async def _add_user(user_info: UserInfoParam, token=Header("token")):
    payload = parse_token(token)
    if payload.get("role_name") == RoleNameEnum.User.value:
        return error_res(ErrorCode.USER_NO_PERMISSION)

    company = company_is_exist(user_info.company_name)
    print(user_info.belong_post, company.company_id)
    # user = get_user_by_post(user_info.company_name)
    # if  user_username :
    #     return error_res(ErrorCode.USER_ISEXIST)
    # user_email = get_user_by_email_null(user_info.email)
    # if  user_email:
    #     return error_res(ErrorCode.EMAIL_ISEXIST)
    user = add_user(user_info)
    return success_res(obj_to_dict(user), SuccessCode.POST)


@user_router.post("/logout", name="退出登录")
async def logout(request: Request, token=Header("token")):
    payload = parse_token(token)
    return success_res(await redis_delete_token(request, payload.get('user_id')), SuccessCode.GET)


@user_router.post("/onlineNum", name="用户在线人数")
async def get_online_num(request: Request, token=Header("token")):
    return success_res(await redis_user_has_login_num(request), SuccessCode.GET)

@user_router.get('/user',name="查询用户列表")
def getall(token=Header("token")):
    payload = parse_token(token)
    if payload.get("role_name") == RoleNameEnum.User.value:
        return error_res(ErrorCode.USER_NO_PERMISSION)
    users = reservoir_sensitivity.query(TbUsers).all()
    if not users:
        raise DataNotExist("用户")
    return success_res(objs_to_dict(users), SuccessCode.GET)
@user_router.post('/update',name="用户信息修改(管理员)")
def update(id,request:UserInfoParam,token=Header("token")):
    payload = parse_token(token)
    if payload.get("role_name") == RoleNameEnum.User.value:
        return error_res(ErrorCode.USER_NO_PERMISSION)
    user = update_users(id,request)
    return success_res(obj_to_dict(user), SuccessCode.PUT)
@user_router.post('/select',name="查询激活或者未激活用户")
def get_activate_is_no(id:int,token=Header("token")):
    payload = parse_token(token)
    if payload.get("role_name") == RoleNameEnum.User.value:
        return error_res(ErrorCode.USER_NO_PERMISSION)
    if id==0:
        user=reservoir_sensitivity.query(TbUsers).filter(TbUsers.is_authorize==0).all()
    if id==1:
        user=reservoir_sensitivity.query(TbUsers).filter(TbUsers.is_authorize==1).all()
    return success_res(objs_to_dict(user),SuccessCode.GET)
@user_router.post('/delete',name="删除用户")
def delete(param:UserID,token=Header("token")):
    payload = parse_token(token)
    if payload.get("role_name") == RoleNameEnum.User.value:
        return error_res(ErrorCode.USER_NO_PERMISSION)
    reservoir_sensitivity.query(TbUsers).filter(TbUsers.user_id==param.user_id).delete()
    reservoir_sensitivity.commit()
    return success_res('',SuccessCode.DELETE)